<?php


/*
 * Edit by xinli
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use cmf\controller\RestBaseController;
use think\facade\Db;
use think\facade\Log;
use api\mall\model\IMWorldMsgModel;
/**
 * Description of IMWorldMsgController
 *
 * @author PC
 */
class IMWorldMsgController extends RestBaseController{

    // 世界消息内存数据
    public static $stWorldMessageArray = [];

    // 世界消息同步时间
    public static $stWorldMessageSyncTime = 0;

    private static $nWorldMsgCount = 100;

    protected function initialize() {
        parent::initialize();
        if (empty($this->user)) {
            $this->error('login');
        }

        // 每个小时同步一次世界消息
        if (empty(self::$stWorldMessageArray) && (time() - self::$stWorldMessageSyncTime) > 60*60) {
            self::$stWorldMessageArray = [];    

            $worldModel = new IMWorldMsgModel();
            $data  = $worldModel
            ->alias('iwm')
            ->join('user u', 'iwm.from_id=u.id')
            ->field('iwm.id,iwm.from_id,iwm.content,iwm.created,u.user_nickname,u.avatar')
            ->where('created','>',time()-24*60*60)
            ->limit(self::$nWorldMsgCount)
            ->select();
            $list = $data->toArray();
            // list转存到stWorldMessageArray
            self::$stWorldMessageArray = $list;
            self::$stWorldMessageSyncTime = time();
        }
    }
    
    public function send() {
        $data = $this->request->post();
        if (empty($data['content'])) {
            $this->error('invalid content');
        }

        $content = $data['content'];

        $worldMsg = [
            'from_id'   => $this->getUserId(),
            'content'   => $content,
            'msg_type'  => 1,
            'created'   => time()
        ];
        $worldModel = new IMWorldMsgModel();
        $worldMsg['id'] = $worldModel->insertGetId($worldMsg);
        array_push(self::$stWorldMessageArray, $worldMsg);

        // 世界消息超过100条，删除最早的一条
        if (count(self::$stWorldMessageArray) > self::$nWorldMsgCount) {
            array_shift(self::$stWorldMessageArray);
        }

        $this->success('ok');
    }

    public function select() {
        $this->success('ok', self::$stWorldMessageArray);
    }
}
